package com.xmjs.baselibrary.view.textview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;

@SuppressLint("AppCompatCustomView")
public class SuperLinkTextView extends TextView {
    OnSuperLinkListener listener;

    public SuperLinkTextView(Context context) {
        super(context);
    }

    public SuperLinkTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public SuperLinkTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * 处理html文本超链接点击事件
     *
     * @param context
     * @param tv
     */
    private void textHtmlClick(Context context, TextView tv) {
        tv.setLinksClickable(true);
        tv.setMovementMethod(LinkMovementMethod.getInstance());
        CharSequence text = tv.getText();
        if (text instanceof Spannable) {
            int end = text.length();
            Spannable sp = (Spannable) text;
            URLSpan[] urls = sp.getSpans(0, end, URLSpan.class);
            SpannableStringBuilder style = new SpannableStringBuilder(text);
            style.clearSpans();// should clear old spans
            for (URLSpan url : urls) {
                MyURLSpan myURLSpan = new MyURLSpan(url.getURL(), context);
                style.setSpan(myURLSpan, sp.getSpanStart(url),
                        sp.getSpanEnd(url), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            }
            tv.setText(style);
        }
    }

    private class MyURLSpan extends ClickableSpan {
        private String mUrl;
        private Context mContext;

        MyURLSpan(String url, Context context) {
            mContext = context;
            mUrl = url;
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setColor(Color.BLACK);
            ds.setUnderlineText(false);
        }

        @Override
        public void onClick(View widget) {
            if (listener != null)
                listener.onClickLink(mUrl);
        }
    }

    public interface OnSuperLinkListener {
        void onClickLink(String url);
    }

    public void setOnSuperLinkListener(OnSuperLinkListener listener) {
        this.listener = listener;
        textHtmlClick(getContext(),this);
    }
}
